<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="档案号" prop="archivesNo">
        <el-input
          v-model="queryParams.archivesNo"
          placeholder="请输入档案号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
	  <el-form-item label="主题" prop="subject">
	    <el-input
	      v-model="queryParams.subject"
	      placeholder="请输入主题"
	      clearable
	      @keyup.enter.native="handleQuery"
	    />
	  </el-form-item>
      <el-form-item label="问题类型" prop="qaTypeId">
		  <el-select v-model="queryParams.qaTypeName" @change="queryTypeChange">
		    <el-option v-for="(item,idx) in qaTypeList" 
		    :label="item.typeName" 
		    :value="item.qaTypeId"
		    :key="idx"
		    ></el-option>
		  </el-select>
      </el-form-item>
      
      <el-form-item label="结案状态" prop="state">
		<el-select v-model="queryParams.state">
		   <el-option value="0" label="未结案">未结案</el-option>
		   <el-option value="1" label="已结案">已结案</el-option>
		</el-select>
		<el-form-item label="起始日期" prop="startDate">
		  <el-date-picker clearable
		    v-model="startDate"
		    type="date"
		    value-format="yyyy-MM-dd"
		    placeholder="请选择起始日期">
		  </el-date-picker>
		</el-form-item>
		<el-form-item label="截止日期" prop="endDate">
		  <el-date-picker clearable
		    v-model="endDate"
		    type="date"
		    value-format="yyyy-MM-dd"
		    placeholder="请选择截止日期">
		  </el-date-picker>
		</el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['consult:groupl:archives:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['consult:groupl:archives:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['consult:groupl:archives:remove']"
        >删除</el-button>
      </el-col>
	  <!--
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['consult:groupl:archives:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="archivesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="archivesGroupId" width="80"/>
	  <el-table-column label="档案号" align="center" prop="archivesNo" />
      <el-table-column label="主题" align="center" prop="subject" />
       <el-table-column label="问题类型" align="center" prop="typeName" />
	    <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="结案状态" align="center" prop="state">
			<template slot-scope="scope">
				<span>{{ scope.row.state ? '已结案':'未结案'  }}</span>
			  </template>
	</el-table-column>		  
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
		  <el-button
		    size="mini"
		    type="text"
		    icon="el-icon-view"
		    @click="handleView(scope.row)"
			v-if="scope.row.state==1"
		  >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
			v-if="scope.row.state==0"
            v-hasPermi="['consult:groupl:archives:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
			v-if="scope.row.state==0"
            v-hasPermi="['consult:groupl:archives:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改咨询团体档案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
	  <el-tabs type="border-card" v-model="tabsValue">
	    <el-tab-pane label="基本信息" name="基本信息">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
					  <el-row>
						  <el-col :span="12">
							<el-form-item label="档案号" prop="archivesNo">
							  <strong>{{form.archivesNo}}</strong>
							</el-form-item>
						  </el-col>
						  <el-col :span="12">
							  <el-form-item label="问题类型" prop="typeName">
							    <el-select v-model="form.typeName" name="typeName" @change="typeChange">
							      <el-option v-for="(item,idx) in qaTypeList" 
							      :label="item.typeName" 
							      :value="item.qaTypeId"
							      :key="idx"
							      ></el-option>
							    </el-select>
							  </el-form-item>
						  </el-col>
						</el-row>	
						
						<el-row>
							<el-col :span="12">
								<el-form-item label="主题" prop="subject">
								  <el-input v-model="form.subject" placeholder="请输入主题" maxlength="50"/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="团体介绍" prop="teamDesc">
								  <el-input v-model="form.teamDesc" placeholder="请输入团体介绍" maxlength="100"/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row style="text-align: center;">
							<el-button type="primary" @click="submitForm">保存</el-button>
						</el-row>
			</el-form>
			
		</el-tab-pane>
	    <el-tab-pane label="咨询记录" :disabled="isadd" name="咨询记录">
			<el-form ref="form3" :model="form2" label-width="120px">
				<el-row >
				<el-button style="float: right; padding: 3px 0" type="text" @click="addrecord">新建记录</el-button>
				</el-row>
				<el-row style="height:400px;overflow-y: scroll;">
				<el-card shadow="always" v-for="(recorditem, recordindex) in form2.recordlist ">
					<div slot="header" class="clearfix">
					    <span>第 <el-input-number v-model="recorditem.recordNumber" controls-position="right" :min="1" ></el-input-number> 次咨询记录（
						  <el-date-picker clearable
							v-model="recorditem.recordDate"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="开始日期">
						  </el-date-picker>
						）</span>
						<el-button style="float: right; padding: 3px 0" type="text" v-if="recordindex>0" @click="delrecord(recordindex)">删除记录</el-button>
					  </div>
					  <div class="text item">
						<el-form-item label="严重程度评估" prop="severity">
							<el-rate
							  v-model="recorditem.severity"
							  text-color="#ff9900">
							</el-rate>
						</el-form-item>
						<el-form-item label="咨询方式" prop="">
							<el-select v-model="recorditem.serviceType" name="serviceType" >
							  <el-option v-for="(item,idx) in serviceTypeList" 
							  :label="item" 
							  :value="item"
							  :key="idx"
							  ></el-option>
							</el-select>
						</el-form-item>	
						<el-row v-for="(item,index) in recorditem.feedbacklist" style="margin-top: 10px;"> 
							<el-col :span="5">
								<el-input v-model="item.feedbackName" placeholder="" maxlength="50" style="direction: rtl;"/>
							</el-col>
							<el-col :span="1">
								<p>&nbsp;</p>
							</el-col>	
							<el-col :span="12">	
								<el-input v-model="item.feedbackContent" placeholder="" maxlength="200" />
							</el-col>
							<el-col :span="1">
								<p>&nbsp;</p>
							</el-col>
							<el-col :span="1">
							<i class="el-icon-minus" style="margin-top: 20px;" @click="delrecordfeedback(recordindex, index)" v-if="index>0"></i>
							</el-col>
						</el-row>
						<el-row style="text-align: right;">
							<i class="el-icon-plus" style="margin-top:20px; margin-right: 170px;" @click="addrecordfeedback(recordindex)"></i>
						</el-row>
					</div>
				</el-card>
				</el-row>
				<el-row style="text-align: center;margin-top: 50px;">
					<el-button type="primary" @click="submitForm2">保存</el-button>
				</el-row>
			</el-form>
		</el-tab-pane>
	    <el-tab-pane label="结案总结" :disabled="isadd" name="结案总结">
			<el-form ref="form3" :model="form3" :rules="rules3" label-width="120px">
				<el-form-item label="咨询效果评估" prop="">
					<el-rate
					  v-model="form3.effect"
					  text-color="#ff9900">
					</el-rate>
				</el-form-item>
				<el-row v-for="(item,index) in form3.feedbacklist" style="margin-top: 10px;"> 
					<el-col :span="5">
						<el-input v-model="item.feedbackName" placeholder="" maxlength="50" style="direction: rtl;"/>
					</el-col>
					<el-col :span="1">
						<p>&nbsp;</p>
					</el-col>	
					<el-col :span="12">	
						<el-input v-model="item.feedbackContent" placeholder="" maxlength="200" type="textarea" :rows="3"/>
					</el-col>
					<el-col :span="1">
						<p>&nbsp;</p>
					</el-col>
					<el-col :span="1">
					<i class="el-icon-minus" style="margin-top: 20px;" @click="delfeedback(index)" v-if="index>0"></i>
					</el-col>
				</el-row>
				<el-row style="text-align: right;">
					<i class="el-icon-plus" style="margin-right: 180px;" @click="addfeedback"></i>
				</el-row>
				<el-row style="text-align: center;margin-top: 50px;">
					<el-button type="primary" @click="submitForm3">保存</el-button>
				</el-row>
			</el-form>
		</el-tab-pane>
	  </el-tabs>
		  
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArchives, getArchives, delArchives, addArchives, updateArchives, getArchivesNo } from "@/api/consult/archives-group";
import { getClose, addClose, updateClose } from "@/api/consult/archives-close";
import { getRecord, saveRecord } from "@/api/consult/archives-record";
import { selectQaType } from "@/api/consult/common";

export default {
  name: "Archives",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 咨询团体档案表格数据
      archivesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        archivesNo: null,
        qaTypeId: null,
		qaTypeName: '',
        subject: null,
        state: null,
		params: {
			
		}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        subject: [
          { required: true, message: "主题不能为空", trigger: "blur" }
        ],
        typeName: [
          { required: true, message: "问题类型不能为空", trigger: "blur" }
        ],
      },
	  form2: {archivesId: '', recordlist: []},
	  form3: {effect:null, feedbacklist: [{feedbackName: '结案总结', feedbackContent:''}], archivesType: 1},
	  rules3: {
	    
	  },
	  qaTypeList: [], // 问题类型
	  startDate: '',
	  endDate: '',
	  isadd: false,
	  addopen: false,
	  tabsValue: '基本信息',
	  serviceTypeList: ['团体咨询（线上）', '团体咨询（线下）','讲座','团体辅导','工作坊','其他']
    };
  },
  created() {
	  this.getQaTypeList();
    this.getList();
  },
  methods: {
	  getQaTypeList() {
	    selectQaType().then(response => {
	      this.qaTypeList = response.data;
	    });
	  },
	  queryTypeChange(val) {
		  this.queryParams.qaTypeId = val;
	  },
	  typeChange(val) {
	  		  this.form.qaTypeId = val;
	  },
	  selectUserName() {
		  this.form.fullName = '';
		  this.form.gender = '';
		  this.form.dept = '';
		  selectUserName(this.form.userName).then(response => {
		    if(response.data) {
				this.form.fullName = response.data.nickName;
				this.form.gender = response.data.sex=='0' ? '男' : response.data.sex=='1' ? '女' : '未知';
				//this.form.birthDate = response.data.nickName;
				this.form.dept = response.data.dept.deptName;
			} else {
				this.$modal.msgError('未找到')
			}
		  });
	  },
    /** 查询咨询团体档案列表 */
    getList() {
      this.loading = true;
	  this.queryParams.params['startDate'] = this.startDate;
	  this.queryParams.params['endDate'] = this.endDate;
      listArchives(this.queryParams).then(response => {
        this.archivesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
	addrecord() {
		let num = this.form2.recordlist.length + 1;
		this.form2.recordlist.push({recordNumber:num, severity:'', serviceType:'', recordDate:'', archivesType: 1,
				feedbacklist:[{feedbackName: '来访者主诉', feedbackContent:''}]});
	},
    // 表单重置
    reset() {
      this.form = {
        archivesGroupId: null,
        userName: null,
        archivesNo: null,
        qaTypeId: null,
        birthDate: null,
        fullName: null,
        gender: null,
        dept: null,
        maritalStatus: null,
        eduLevel: null,
        mobile: null,
      };
	  this.form2 = {recordlist: []};
	  this.addrecord(1);
	  this.form3 = {effect:null, feedbacklist: [{feedbackName: '结案总结', feedbackContent:''}], archivesId: ''}
	  this.resetForm("form3");
      this.resetForm("form");
	  this.tabsValue = '基本信息';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
		this.startDate = '';
		this.endDate =  '';
		this.queryParams.qaTypeId = '';
		this.queryParams.qaTypeName = '';
		this.resetForm("queryForm");
		this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.archivesGroupId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
	handleView(row) {
		const archivesGroupId = row.archivesGroupId;
		console.log(archivesGroupId)
		this.$router.push("/consult/archives/view/g/" + archivesGroupId);
	},
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加咨询团体档案";
	  this.isadd = true;
	  this.addopen = true;
	  getArchivesNo().then(response => {
		  this.form.archivesNo = response.msg;
	  });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const archivesGroupId = row.archivesGroupId || this.ids
      getArchives(archivesGroupId).then(response => {
        this.form = response.data;
        this.open = true;
		this.isadd = false;
		this.addopen = false;
        this.title = "修改咨询团体档案";
		
		//this.form3.archivesGroupId = archivesGroupId;
		getClose(this.form.archivesId).then(response => {
				  if(response.data)
					this.form3 = response.data;
		});
		
		getRecord(this.form.archivesId).then(response => {
				  if(response.data && response.data.length>0)
					this.form2.recordlist = response.data;
		});
		
      });
	  
    },
	/** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.archivesGroupId != null) {
            updateArchives(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
			  this.getList();
			  if(this.addopen)
			  	 this.tabsValue = '咨询记录';
            });
          } else {
            addArchives(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
			  this.form.archivesGroupId = response.data.archivesGroupId;
			  this.isadd = false;
			  this.getList();
			  if(this.addopen)
				this.tabsValue = '咨询记录';
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const archivesGroupIds = row.archivesGroupId || this.ids;
      this.$modal.confirm('是否确认删除咨询团体档案编号为"' + archivesGroupIds + '"的数据项？').then(function() {
        return delArchives(archivesGroupIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/archives/export', {
        ...this.queryParams
      }, `archives_${new Date().getTime()}.xlsx`)
    },
	addrecordfeedback(index) {
		this.form2.recordlist[index].feedbacklist.push({feedbackName: '', feedbackContent:''})
	},
	delrecordfeedback(index, fbindex) {
		this.form2.recordlist[index].feedbacklist.splice(fbindex,1);
	},
	delrecord(index) {
		this.form2.recordlist.splice(index,1);
	},
	submitForm2() {
		let flag = false;
		
		for(let index=0;index<this.form2.recordlist.length;index++) {
			let item = this.form2.recordlist[index];
			if(!item.recordNumber) {
				this.$modal.msgError("请输入次数");
				flag = true;
				break
			}
			if(item.severity=='') {
				this.$modal.msgError("请选择严重程度");
				flag = true;
				break
			}
			if(item.serviceType=='') {
				this.$modal.msgError("请选择咨询方式");
				flag = true;
				break
			}
			if(item.recordDate=='') {
				this.$modal.msgError("请选择开始日期");
				flag = true;
				break;
			}
			/*let feedbacklist = item.feedbacklist;
			for(let i=0;i<feedbacklist.length;i++) {
				let item2 = feedbacklist[i];
				if(item2.feedbackContent=='' || item2.feedbackName=='') {
					this.$modal.msgError("请填写完整");
					flag = true;
					break;
				}
			} */
			if(flag) break;
		}
		if(flag) return false;
		this.form2.recordlist.forEach(item=>{
			item.archivesId = this.form.archivesId;
		})
		//this.form2.archivesId = this.form.archivesId;
				this.$modal.loading("保存中，请稍候！");
		  saveRecord(this.form2.recordlist).then(response => {
			this.$modal.msgSuccess("保存成功");
			this.$modal.closeLoading();
		  });
	},
	addfeedback() {
		this.form3.feedbacklist.push({feedbackName: '', feedbackContent:''})
	},
	delfeedback(index) {
		this.form3.feedbacklist.splice(index,1);
	},
	submitForm3() {
		this.$refs["form3"].validate(valid => {
			if (valid) {
				let flag = false;
				this.form3.feedbacklist.forEach(item=> {
					if(item.feedbackContent=='' || item.feedbackName=='') {
						this.$modal.msgError("请填写完整");
						flag = true;
						return false;
					}
					
				})
				if(flag) return false;
			  let _this = this;
			  this.$modal.confirm('结案后不可修改，是否保存？').then(function() {
			    if (_this.form3.archivesCloseId != null) {
			      return updateClose(_this.form3);
			    } else {
			      _this.form3.archivesId	= _this.form.archivesId;
			      return addClose(_this.form3);
			    }
				
			  }).then(() => {
			    this.getList();
			    this.$modal.msgSuccess("保存成功");
				this.open = false;
			  }).catch(() => {});
			  
			  
			  
			}
		});
	}
  }
};
</script>
